import { doFetch, getFetch } from '@/utils/doFetch';
import { useModel, useLocation, history } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, message, notification } from 'antd';
import { useEffect } from 'react';
import { io } from 'socket.io-client';
import LayoutDom from './layoutdom';
import useWxCode from '@/utils/useWxCode';
import useCurrentUser from '@/utils/useCurrentUser';
import { v4 as uuidv4 } from 'uuid';



function Layout() {

  const { setInitialState, currentUser, getUser } = useCurrentUser();

  const dothing = useRequest(
    async () => {
      let res = await getFetch({
        url: '/joinOrgInvitation',
        params: {
          handleResult: 1
        },
      });
      return res?.data?.dataList?.length ?? 0;
    },
    {
      debounceWait: 400,
      onSuccess: (res) => {
        setInitialState(s => ({
          ...s,
          unreadJoinOrgInvitationCount: res,
        }))
      }
    },
  );


  const { runAsync } = useRequest(doFetch, {
    manual: true,
    debounceWait: 1000,
    onSuccess: async (res) => {
      if (res.code !== 0) {
        message.destroy();
        if (res.code === 438) {
          // 获取当前 URL
          const currentUrl = window.location.href;
          // 使用 URL 构造函数解析当前的 URL
          const url = new URL(currentUrl);
          // 清除所有的 query 参数
          url.search = '';
          // 使用 history.replaceState 更新 URL 而不重新加载页面
          history.replace({
            pathname: url.pathname,
            search: url.search,
            hash: url.hash
          });
        }
        return;
      }
      await getUser.runAsync();
      message.success('绑定成功,可以使用微信扫码登录目前账号');
      // 获取当前 URL
      const currentUrl = window.location.href;
      // 使用 URL 构造函数解析当前的 URL
      const url = new URL(currentUrl);
      // 清除所有的 query 参数
      url.search = '';
      // 使用 history.replaceState 更新 URL 而不重新加载页面
      history.replace({
        pathname: url.pathname,
        search: url.search,
        hash: url.hash
      });
    }
  })

  useWxCode(async (state, code, pathname) => {
    if (!code || !state) {
      return;
    }
    if (!currentUser?.isBindWx) {
      await runAsync({ url: '/system/userBindWx', params: { code, state } });
    }
  })

  useEffect(() => {
    // const socket = io(SOCKET_APP_URL, {
    //   autoConnect: false,
    //   query: { userId: localStorage.getItem('ID') }
    // });
    // socket.connect();
    // socket.on('message', (data) => {
    //   notification.info({
    //     message: (
    //       <div className="spread">
    //         <b>{data.param.title}</b>
    //       </div>
    //     ),
    //     duration: 0,
    //     description: (
    //       <span
    //         style={{ cursor: 'pointer' }}
    //         onClick={() => {
    //           if (data.msgModel !== 'ITEM') return;
    //           setInitialState((s) => ({
    //             ...s,
    //             drawerAll: {
    //               ...s.drawerAll,
    //               item: {
    //                 id: data.param.itemId,
    //               },
    //               open: true,
    //             },
    //             refreshlist: () => { },
    //           }));
    //         }}
    //       >
    //         {data?.messageInfo}
    //       </span>
    //     ),
    //     placement: 'bottomRight',
    //     btn: data.msgModel === 'JOIN_ORG' ? <Button onClick={() => {
    //       doFetch({ url: "/user/joinOrg", params: { joinOrgInvitationId: data.param.id }, method: "PUT" }).then((res) => {
    //         if (res.code === 0) {
    //           message.success('加入团队成功');
    //           getUser.run();
    //           notification.destroy();
    //         }
    //       })
    //     }}>同意</Button> : null
    //   });
    // });
    // socket.on('onlineUsers', (data) => {
    //   setInitialState((s) => {
    //     const a = data,
    //       b = s.activeUserIdList ?? [];
    //     if (a.length === b.length && a.sort().toString() === b.sort().toString())
    //       return {
    //         ...s,
    //       };
    //     else
    //       return {
    //         ...s,
    //         activeUserIdList: data,
    //       };
    //   });
    // });
    // return () => {
    //   // 关闭 WebSocket 连接
    //   socket.disconnect();
    // };
  }, []);

  return <LayoutDom ></LayoutDom>;
}

export default Layout;
